<template>
  <div class="box-content">
    <div class="navigation"><span v-if="userInfo.type == 1">景区列表/</span>景点列表/设备列表<span class="check" @click="$router.go(-1)">返回上一级</span></div>
    <!--搜索-->
    <div class="mt-3">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-input type="text" size="small" v-model="search.inputName" :clearable="true" placeholder="输入关键字(设备名称或设备编号)"></el-input>
        </el-col>
        <el-col :span="18">
          <el-button type="primary" size="small" @click="onSearch">查询</el-button>
          <el-button type="primary" size="small" @click="createAccount">绑定设备</el-button>
          <el-button type="primary" size="small" @click="addEq">添加</el-button>
        </el-col>
      </el-row>
    </div>
    <!--表格-->
    <div class="mt-3">
      <el-table
              :data="userData"
              v-loading="loading"
              align="center"
              :element-loading-text="loadText"
              :header-cell-style="tableHeaderColor"
              stripe
              style="width: 100%">
        <el-table-column
                prop="id"
                align="center"
                label="编号"
                width="100"
        >
        </el-table-column>
        <el-table-column
                prop="ta_name"
                align="center"
                width="100"
                label="景点"
        >
        </el-table-column>
        <el-table-column
                prop="dvc_name"
                align="center"
                width="80"
                label="设备分类"
        >
        </el-table-column>
        <el-table-column
                prop="dv_name"
                align="center"
                width="100"
                label="设备名"
        >
        </el-table-column>
        <el-table-column
                prop="sn"
                align="center"
                width="100"
                label="设备编号"
        >
        </el-table-column>
        <el-table-column
                prop="longitude"
                align="center"
                width="120"
                label="经度"
        >
        </el-table-column>
        <el-table-column
                prop="latitude"
                align="center"
                width="120"
                label="纬度"
        >
        </el-table-column>

        <el-table-column
                prop="address"
                align="center"
                width="200"
                label="放置地址"
        >
        </el-table-column>
        <el-table-column
                prop="status"
                align="center"
                label="状态"
        >
          <template slot-scope="scope">
            <el-switch
                    v-model="scope.row.status"
                    :active-value="1"
                    :inactive-value="2"
                    @change=changeStatus(scope.row)></el-switch>
          </template>

        </el-table-column>
        <el-table-column
                label="创建时间"
                align="center"
                width="100">
          <template slot-scope="scope">
            <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(0, 11):'无'}}</div>
            <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(11 ):'无'}}</div>
          </template>
        </el-table-column>
        <el-table-column
                label="操作"
                align="center"
                fixed="right"
                width="160">
          <template slot-scope="scope">
            <el-button
                    size="small"
                    type="primary"
                    @click="handleEdit(scope.row)">编辑
            </el-button>
            <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete(scope.row)">解绑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-3 float-right">
        <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageInfo.current_page"
                :page-size="pageInfo.per_page"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageInfo.total">
        </el-pagination>
      </div>
    </div>
    <!--新增对话框-->
    <el-dialog title="绑定设备"
               :visible.sync="dialogFormVisible"
               :close-on-click-modal="false"
               width="600px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px"
               element-loading-text="未绑定设备获取中"
               element-loading-spinner="el-icon-loading"
               v-loading="loadingDialig">
        <el-form-item label="设备" prop="dv_id">
          <el-select v-model="form.dv_id" placeholder="请选择要绑定到该景点的设备"  :clearable="true" style="width: 450px;">
            <el-option
                    v-for="item in eqData"
                    :key="item.id"
                    :label="item.id + '/' +item.dv_name"
                    :value="item.id">
            </el-option>
          </el-select>
          <!--<EqData @changeName="changeName"></EqData>-->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" v-if="!dialog.isEdit" :loading="loadingCreate"
                   @click="submitCostomer('form')">{{loadingCreate?'创建中':'点击创建'}}
        </el-button>
        <el-button type="primary" v-if="dialog.isEdit" :loading="loadingCreate" @click="submitCostomer('form')">
          {{loadingCreate?'修改中':'点击修改'}}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :title="dialog.title"
               :visible.sync="dialogFormVisible1"
               :close-on-click-modal="false"
               width="600px">
      <el-form :model="form1" :rules="rules1" ref="form1" label-width="100px" v-loading="loadingDialig">
        <el-form-item label="设备分类ID" prop="dvc_ids">
          <el-cascader
                  v-model="form1.dvc_ids"
                  style="width: 450px;"
                  placeholder="设备分类ID"
                  :options="dvcData"
                  @change="handleChangeTree"
                  filterable
                  change-on-select
          ></el-cascader>
        </el-form-item>
        <el-form-item label="设备名" prop="dv_name1">
          <el-input v-model="form1.dv_name1" placeholder="请输入设备名" style="width: 450px;"></el-input>
        </el-form-item>
        <el-form-item label="设备编号" prop="sn1">
          <el-input v-model="form1.sn1" placeholder="请输入设备编号" style="width: 450px;"></el-input>
        </el-form-item>
        <el-form-item label="设备经度" prop="longitude1">
          <el-input type="number" v-model="form1.longitude1" placeholder="请输入设备经度" :clearable="true" style="width: 450px;"></el-input>
        </el-form-item>
        <el-form-item label="设备纬度" prop="latitude1">
          <el-input type="number" v-model="form1.latitude1" placeholder="请输入设备纬度" :clearable="true" style="width: 450px;"></el-input>
        </el-form-item>
        <el-form-item label="设备放置地址" prop="address1">
          <el-input type="text" v-model="form1.address1" placeholder="请输入设备放置地址" :clearable="true" style="width: 450px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" :loading="loadingCreate1" v-if="!dialog.isEdit"
                   @click="submitCostomer1('form1')">{{loadingCreate1?'添加并绑定中':'添加并绑定'}}
        </el-button>
        <el-button type="primary" :loading="loadingCreate1" v-if="dialog.isEdit"
                   @click="submitCostomer1('form1')">{{loadingCreate1?'修改中':'修改'}}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import EqData from '../../../components/eqData';
    export default {
        name: "accountList",
        components: {
            EqData
        },
        data() {
            return {
                dialog1: {
                    title:''
                },
                userInfo:{},
                baseId: null,
                pageInfo: {
                    per_page: 10,
                    total: 0,
                    current_page: 1
                },
                loadText: '数据加载中',
                userData: [],  // 设备列表
                eqData: [], // 未绑定的设备列表
                searchStr: '',
                search: {
                    inputName: ''
                },
                loading: false,
                loadingDialig: false,
                loadingCreate: false,
                loadingCreate1: false,
                dialogFormVisible: false,
                dialogFormVisible1: false,
                dvcData:[],
                form1: {
                    dvc_ids:[],
                    dvc_id1: '',
                    dv_name1: '',
                    sn1: '',
                    longitude1: '',
                    latitude1: '',
                    address1: '',
                },
                rules1: {
                    dvc_ids: [
                        {required: 'true', message: '请选择设备分类ID', trigger: 'change'}
                    ],
                    dv_name1: [
                        {required: 'true', message: '请输入设备名', trigger: 'change'}
                    ],
                    sn1: [
                        {required: 'true', message: '请输入设备编号', trigger: 'change'}
                    ],
                },
                form: {
                    dv_id: '',
                },
                dialog: {
                    title: '',
                    isEdit: false
                },
                rules: {
                    dv_id: [
                        {required: 'true', message: '请选择要绑定到该景点的设备', trigger: 'change'}
                    ]
                }
            }
        },
        watch: {
            dialogFormVisible: function (val) {
                if (!val) {
                    Object.keys(this.form).forEach(key => this.form[key] = '');
                    this.$refs['form'].resetFields();
                    this.form.dvc_id1 = '';
                } else {
                    this.getUnBindEq();
                }
            }
        },
        created() {
            this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
            this.getFenLeiList();
            this.getAccountList();
        },
        methods: {
            addEq() {
              this.dialogFormVisible1 = true;
                this.dialog.title = '添加并绑定设备';
            },
            handleEdit(val) {
                this.baseId = val.id;
                this.dialog.title = '编辑设备';
                this.dialog.isEdit = true;
                this.dialogFormVisible1 = true;
                this.loadingDialig = true;
                this.$http.get('api/auth/device/' + val.id)
                    .then((result) => {
                        this.form1.dvc_ids = [];
                        if (result.status_code == 200) {
                            this.dvcData.forEach(item1=>{
                                if (item1.value == result.data.dvc_id) {
                                    this.form1.dvc_ids.push(result.data.dvc_id);
                                } else {
                                    if (item1.children && item1.children.length>0) {
                                        item1.children.forEach(item2=>{
                                            if (item2.value == result.data.dvc_id) {
                                                this.form1.dvc_ids.push(item1.value);
                                                this.form1.dvc_ids.push(item2.value);
                                            } else {
                                                if (item2.children && item2.children.length>0) {
                                                    item2.children.forEach(item3=>{
                                                        if (item3.value == result.data.dvc_id) {
                                                            this.form1.dvc_ids.push(item1.value);
                                                            this.form1.dvc_ids.push(item2.value);
                                                            this.form1.dvc_ids.push(item3.value);
                                                        }
                                                    })
                                                }
                                            }
                                        })
                                    }
                                }
                            });
                            this.form1.dvc_id1 = result.data.dvc_id;
                            this.form1.dv_name1 = result.data.dv_name;
                            this.form1.sn1 = result.data.sn;
                            this.form1.address1 = result.data.address;
                            this.form1.longitude1 = result.data.longitude;
                            this.form1.latitude1 = result.data.latitude;


                        } else {
                            this.$message.warning(result.msg);
                        }
                        this.loadingDialig = false;
                        this.loadingCreate = false;
                    })
                    .catch((err) => {
                        this.loadingDialig = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            handleChangeTree(val) {
                if (val) {
                    if (val.length == 1) {
                        this.form1.dvc_id1 = val[0]
                    } else if (val.length == 2) {
                        this.form1.dvc_id1 = val[1]
                    } else if (val.length == 3) {
                        this.form1.dvc_id1 = val[2]
                    }
                }
                // console.info('val', this.form.dvc_id1);
            },
            getFenLeiList() {
                this.$http.get('api/auth/deviceCategory?@action=cateTree')
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.dvcData = result.data;
                        } else {
                            this.$message.warning(result.msg);
                        }
                    })
                    .catch((err) => {
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            changeName(val) {
                this.form.dv_id = val;
            },
            createAccount() {
                this.dialog.title = '绑定设备';
                this.dialog.isEdit = false;
                this.dialogFormVisible = true;
            },
            getUnBindEq() {
                this.loadingDialig = true;
                this.$http.get('api/auth/device?@action=unBindAttraction')
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.eqData = result.data.data;
                        } else {
                            this.$message.warning(result.msg);
                        }
                        this.loadingDialig = false;
                    })
                    .catch((err) => {
                        this.loadingDialig = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            changeStatus(val) {
                let params = {
                    dvc_id: val.dvc_id,
                    status: val.status
                };
                this.$http.put('api/auth/device/' + val.id, params)
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.$message({
                                type: 'success',
                                message: result.msg,
                                during: 1000
                            });
                        } else {
                            this.$message.warning(result.msg);
                        }
                    })
                    .catch((err) => {
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            getAccountList() {
                this.loading = true;
                this.$http.get('api/auth/device?ta_id=' + this.$route.params.eq + this.searchStr, {
                    params: {
                        pageSize: this.pageInfo.per_page,
                        page: this.pageInfo.current_page
                    }
                })
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.userData = result.data.data;
                            this.pageInfo.total = result.data.total;
                        } else {
                            this.$message.warning(result.msg);
                        }
                        this.loading = false;
                    })
                    .catch((err) => {
                        this.loading = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            onSearch() {
                this.searchStr = "";
                if (this.search.inputName) {
                    this.searchStr += `&keyword=${this.search.inputName}`;
                }
                this.pageInfo.current_page = 1;
                this.getAccountList();
            },
            addConStr() {
                if (this.searchStr.length > 0) {
                    this.searchStr += '&';
                } else {
                    this.searchStr += '?';
                }
            },
            submitCostomer(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.creatShanHu();
                    } else {
                        return false;
                    }
                });
            },
            submitCostomer1(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.creatAndBind();
                    } else {
                        return false;
                    }
                });
            },
            creatAndBind() {
                let params={
                    ta_id:this.$route.params.eq,
                    dvc_id:this.form1.dvc_id1,
                    dv_name:this.form1.dv_name1,
                    sn:this.form1.sn1,
                    address:this.form1.address1,
                    longitude:this.form1.longitude1,
                    latitude:this.form1.latitude1,
                };
                this.loadingCreate1 = true;
                if (!this.dialog.isEdit) {
                    this.$http.post('api/auth/device', params)
                        .then((result) => {
                            if (result.status_code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: result.msg,
                                    during: 1000
                                });
                                this.getAccountList();
                                this.dialogFormVisible1 = false;
                            } else {
                                this.$message.warning(result.msg);
                            }
                            this.loadingCreate1 = false;

                        })
                        .catch((err) => {
                            this.loadingCreate1 = false;
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                } else {
                    this.$http.put('api/auth/device/'+ this.baseId, params)
                        .then((result) => {
                            if (result.status_code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: result.msg,
                                    during: 1000
                                });
                                this.getAccountList();
                                this.dialogFormVisible1 = false;
                            } else {
                                this.$message.warning(result.msg);
                            }
                            this.loadingCreate1 = false;

                        })
                        .catch((err) => {
                            this.loadingCreate1 = false;
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }

            },
            creatShanHu() {
                this.loadingCreate = true;
                let params={
                        dv_id:this.form.dv_id,
                        ta_id:this.$route.params.eq
                    };
                    this.$http.post('api/auth/device?@action=bindTourismAttraction', params)
                        .then((result) => {
                            if (result.status_code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: result.msg,
                                    during: 1000
                                });
                                this.getAccountList();
                                this.dialogFormVisible = false;
                            } else {
                                this.$message.warning(result.msg);
                            }
                            this.loadingCreate = false;

                        })
                        .catch((err) => {
                            this.loadingCreate = false;
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })

            },
            handleDelete(val) {
                this.$confirm('此操作将此设备解绑, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let params ={
                        dv_id:val.id,
                        ta_id:this.$route.params.eq
                    };
                    this.$http.post('api/auth/device?@action=unbindTourismAttraction',params)
                        .then((result) => {
                            if (result.status_code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: result.msg,
                                    during: 1000
                                });
                                this.getAccountList();
                            } else {
                                this.$message.warning(result.msg);
                            }
                        })
                        .catch((err) => {
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }).catch(() => {
                });
            },
            handleSizeChange(val) {
                this.pageInfo.current_page = 1;
                this.pageInfo.per_page = val;
                this.getAccountList();
            },
            handleCurrentChange(val) {
                this.pageInfo.current_page = val;
                this.getAccountList();
            },
            tableHeaderColor({row, column, rowIndex, columnIndex}) {
                if (rowIndex === 0) {
                    return 'background-color: #FAFAFA;color: #000;font-weight: 500;height:54px;font-size:14px'
                }
            },
        }
    }
</script>

<style lang="less" scoped>
</style>